import { ref, onUnmounted } from 'vue'
import { io, Socket } from 'socket.io-client'

export function useWebSocket(url: string, options?: any) {
    const socket = ref<Socket | null>(null)
    const isConnected = ref(false)
    const error = ref<string | null>(null)

    const connect = () => {
        try {
            const token = localStorage.getItem('token')
            socket.value = io(url, {
                auth: {
                    token
                },
                ...options
            })

            socket.value.on('connect', () => {
                isConnected.value = true
                error.value = null
            })

            socket.value.on('disconnect', () => {
                isConnected.value = false
            })

            socket.value.on('connect_error', (err) => {
                error.value = err.message
                isConnected.value = false
            })

        } catch (err) {
            error.value = err instanceof Error ? err.message : 'WebSocket connection failed'
        }
    }

    const disconnect = () => {
        if (socket.value) {
            socket.value.disconnect()
            socket.value = null
            isConnected.value = false
        }
    }

    const emit = (event: string, data?: any) => {
        if (socket.value && isConnected.value) {
            socket.value.emit(event, data)
        }
    }

    const on = (event: string, callback: (...args: any[]) => void) => {
        if (socket.value) {
            socket.value.on(event, callback)
        }
    }

    const off = (event: string, callback?: (...args: any[]) => void) => {
        if (socket.value) {
            socket.value.off(event, callback)
        }
    }

    // 自动清理
    onUnmounted(() => {
        disconnect()
    })

    return {
        socket: socket.value,
        isConnected,
        error,
        connect,
        disconnect,
        emit,
        on,
        off
    }
}